package net.wanho.security.filter;

import cn.hutool.json.JSONUtil;
import net.wanho.security.token.JwtToken;
import net.wanho.vo.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-11-13 16:22
 * Description：<描述>
 */
@Component
public class JwtFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("JwtFilter.doFilterInternal.......................");

        // 如果是登录请求，则直接放行
        String uri = request.getRequestURI();
        if (uri.contains("/auth/login")){
            filterChain.doFilter(request,response);
            return;
        }

        // 如果是其他请求，则需要验证token
        String token = request.getHeader("Authentication");
        if (StringUtils.isEmpty(token)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(AjaxResult.error(HttpStatus.UNAUTHORIZED.value(), "请先登录再操作！")));
            return;
        }
        token = token.replace("Bearer ", "");

        // 调用security认证
        Authentication authentication = new JwtToken(token);
        SecurityContextHolder.getContext().setAuthentication(authentication); // 将认证信息放入上下文

        filterChain.doFilter(request,response);
    }
}
